package com.iwdnb.gkgz.common.quota;

import java.util.Arrays;

public class StockBIASWithHMA {

    // 计算权重移动平均值（WMA）
    private static double weightedMovingAverage(double[] prices, int period) {
        double sum = 0.0;
        double denom = 0.0;
        for (int i = 0; i < period; i++) {
            sum += prices[i] * (period - i);
            denom += (i + 1);
        }
        return sum / denom;
    }

    // 计算赫尔均线（HMA）
    private static double[] calculateHMA(double[] prices, int period) {
        // 步骤1: 计算权重移动平均值（WMA）的差值
        double[] wmaDifference = new double[prices.length - period + 1];
        for (int i = period - 1; i < prices.length; i++) {
            double[] tempArray = Arrays.copyOfRange(prices, i - period + 1, i + 1);
            double wmaFull = weightedMovingAverage(tempArray, period);
            double wmaHalf = weightedMovingAverage(Arrays.copyOfRange(tempArray, period / 2, period), period / 2) * 2;
            wmaDifference[i - (period - 1)] = wmaHalf - wmaFull;
        }

        // 步骤2: 计算HMA
        double[] hma = new double[wmaDifference.length - (int)Math.sqrt(period) + 1];
        for (int i = (int)Math.sqrt(period) - 1; i < wmaDifference.length; i++) {
            double[] tempArray = Arrays.copyOfRange(wmaDifference, i - (int)Math.sqrt(period) + 1, i + 1);
            hma[i - ((int)Math.sqrt(period) - 1)] = weightedMovingAverage(tempArray, (int)Math.sqrt(period));
        }

        return hma;
    }

    // 计算乖离率
    private static double calculateBIAS(double currentPrice, double hma) {
        return ((currentPrice - hma) / hma) * 100;
    }

    public static void main(String[] args) {
        // 模拟数据
        double[] prices = {
            // 填入至少需要60日的股票价格数据
        };

        int period = 60;
        double[] hma = calculateHMA(prices, period);
        for (int i = 0; i < hma.length; i++) {
            if (i + period < prices.length) {
                // 计算当前价格与HMA的乖离率
                double bias = calculateBIAS(prices[i + period], hma[i]);
                System.out.println("Day " + (i + period + 1) + ": BIAS = " + bias + "%");
            }
        }
    }
}

